package com.learn.sort;

/**
 * 排序算法
 */
public class SortDemo {

    //归并排序
    public void sort1(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        process(arr, 0, arr.length - 1);
    }


    public void process(int[] arr, int L, int R) {
        if (L == R) {
            return;
        }

        int mid = L + ((R - L) >> 1);
        //左边变成排序
        process(arr, L, mid);
        //右边变成有序
        process(arr, mid + 1, R);
        //合并两个有序数组
        mergesort(arr, L, mid, R);
    }


    public void mergesort(int[] arr, int L, int mid, int R) {
        int[] help = new int[R - L + 1];
        //左边数组大小
        int i = 0;
        int leftStart = L;
        int rightStart = mid + 1;
        //右边数组大小
        while (leftStart <= mid && rightStart <= R) {
            help[i++] = arr[leftStart] <= arr[rightStart] ? arr[leftStart++] : arr[rightStart++];
        }

        while (leftStart <= mid) {
            help[i++] = arr[leftStart++];
        }
        while (rightStart <= R) {
            help[i++] = arr[rightStart++];
        }

        for (int j = 0; j < help.length; j++) {
            arr[L + j] = help[j];
        }

    }


    //求数组的最小和

    public int minSum(int[] arr) {
        if (arr == null || arr.length < 2) {
            return 0;
        }
        return minProcess(arr, 0, arr.length - 1);
    }

    public int minProcess(int[] arr, int L, int R) {
        if (L == R) {
            return 0;
        }

        int mid = L + ((R - L) >> 1);
        //左侧的最小和，右边的最小和，合并后的最小和
        return minProcess(arr, L, mid) + minProcess(arr, mid + 1, R) + minMergesort(arr, L, mid, R);
    }


    public int minMergesort(int[] arr, int L, int mid, int R) {
        int[] help = new int[R - L + 1];
        //左边数组大小
        int i = 0;
        int leftStart = L;
        int rightStart = mid + 1;
        int res = 0;
        while (leftStart <= mid && rightStart <= R) {
            res+= arr[leftStart] < arr[rightStart] ? arr[R - rightStart + 1] * arr[rightStart] : 0;
            help[i++] = arr[leftStart] < arr[rightStart] ? arr[leftStart++] : arr[rightStart++];
        }

        while (leftStart <= mid) {
            help[i++] = arr[leftStart++];
        }
        while (rightStart <= R) {
            help[i++] = arr[rightStart++];
        }

        for (int j = 0; j < help.length; j++) {
            arr[L + j] = help[j];
        }
        return res;

    }


    public static void main(String[] args) {
        SortDemo sortDemo = new SortDemo();
        int[] arr = {1, 4, 2, 3, 5};
        sortDemo.sort1(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
